<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/12/2 0002
 * Time: 11:09
 */

namespace app\api\controller\Money;

use app\api\controller\HomeCommon;
use app\api\model\SendCode;
use app\api\model\User;
use app\common\controller\UtilCommon;
use app\lib\exception\FailedException;
use app\Validate\PageMustValidate;
use think\Db;
use think\Exception;
use think\Request;
use app\api\model\Money as MoneyService ;
use app\api\model\MoneyRecord;
use app\api\model\Config;


class Money extends HomeCommon
{
    /**
     * 获取邀请页面信息
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getInviteInfo(Request $request){
        $post = $request->post();
        $userService = new User();
        $where["id"] = $post['user_id'];
        $userModel = $userService->where($where)->find();
        if($userModel == null){
            throw new FailedException(['msg'=>'用户不存在,请尝试重新登陆']);
        }

        //获取其他页面数据
        $configService = new Config();
        $list = $configService->where("id in (11,14,15,16)")->select();
        $data = [];
        $data["invite_code"] = $userModel["invite_code"];
        foreach ($list as $k => $v){
            if($v["id"] == 11){ $data["isOpen"]=$v["v"];}
            if($v["id"] == 14){ $data["invite_img"]=$v["v"];}
            if($v["id"] == 15){ $data["down_ad_img"]=$v["v"];}
            if($v["id"] == 16){ $data["down_ios_img"]=$v["v"];}
        }
        return writeJson("200",$data);

    }

    /**
     * 获取钱包明细
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getMoney(Request $request){
        $post = $request->post();
        $moneyModel = $this->getMoneyByUserId($post['user_id']);
        if($moneyModel == null){ throw new FailedException(['msg'=>'用户钱包不存在，请联系客服人员']);}
        $data["moneyNow"] = $moneyModel["money"];//[可提现收入-钱包表余额]

        $MoneyRecordService = new MoneyRecord();
        $where = [['money_source_type','eq',0],['user_id','eq',$post['user_id']],['pay_status','in',[0,1,2]]];
        $data["moneyAll"] = $MoneyRecordService->where($where)->sum("money");//[累计收入-收入账单表总和]

        $where = [['money_source_type','eq',0],['user_id','eq',$post['user_id']],['pay_status','eq',0]];
        $data["moneyStay"] = $MoneyRecordService->where($where)->sum("money");//[待到账收入-佣金未支付总数]

        return writeJson("200",$data);
    }

    /**
     * 获取佣金账单明细
     * 入参:page_number,page,(pay_status)
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\exception\DbException
     * @throws \app\lib\exception\ParameterException
     */
    public function getMoneyInviteRecord(Request $request){
        (new PageMustValidate())->goCheck();
        $post = $request->post();
        $where["money_source_type"] = 0;  //账单来源(0拥金 1提现)
        if(isset($post["pay_status"])){
            //支付状态  (0待到账 1已到账)
            if($post["pay_status"] == 0){
                $where["pay_status"] = 0;
            }
            if($post["pay_status"] == 1){
                $where["pay_status"] = 2;
            }
        }

        $where["user_id"] = $post["user_id"];//当前用户
        $where["money_type"] = 0;         //金额类型 0 收入

        /*
        [SQL]select
        ifNull(om_user.nickname,'') as nickname,
        ifNull(om_user.head_img,'') as head_img,
        om_money_record.create_time,
        om_money_record.money,
        om_money_record.pay_status
        from om_money_record
        inner join om_user on om_money_record.source_user_id = om_user.id
        where money_source_type = 0 and pay_status = 1 and money_type = 0*/
        $recordService = new MoneyRecord();
        $dataList = $recordService
            ->field("ifNull(om_user.nickname,'') as nickname,ifNull(om_user.head_img,'') as head_img,om_money_record.create_time,om_money_record.money,om_money_record.pay_status")
            ->join("om_user","om_money_record.source_user_id = om_user.id")
            ->where($where)
            ->order("om_money_record.create_time")
            ->paginate($post['page_number'], false, ['page' => $post['page']]);

        foreach ($dataList as $k=>$v){
            $v["pay_status_str"] = $recordService->getPayStatusStr($v["pay_status"]);
        }
        $result = [
            'count'=>$dataList->total(),
            'data'=>$dataList
        ];
        return writeJson(200,$result);
    }

    /**
     * 获取提现账单明细
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\exception\DbException
     * @throws \app\lib\exception\ParameterException
     */
    public function getMoneyOutRecord(Request $request){
        (new PageMustValidate())->goCheck();
        $post = $request->post();
        $recordService = new MoneyRecord();
        $where["money_source_type"] = 1;  //账单来源(0拥金 1提现)
        $where["user_id"] = $post["user_id"];//当前用户
        $where["money_type"] = 1;         //金额类型 1 支出
        $dataList = $recordService
            ->field("money,audit_status,create_time,audit_time_remark,pay_type,pay_status")
            ->where($where)
            ->order("create_time desc")
            ->paginate($post['page_number'], false, ['page' => $post['page']]);

        foreach ($dataList as $k=>$v){
            $v["audit_status_str"] = $recordService->getAuditStatusStr($v["audit_status"]);
            $v["pay_type_str"] = $recordService->getPayTypeStr($v["pay_type"]);
            $v["pay_status_str"] = $recordService->getPayStatusStr($v["pay_status"]);
        }

        $result = [
            'count'=>$dataList->total(),
            'data'=>$dataList
        ];
        return writeJson(200,$result);
    }

    /**
     * 查看我的下级
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     * @throws \think\exception\DbException
     * @throws \app\lib\exception\ParameterException
     */
    public function getInviteUser(Request $request){
        (new PageMustValidate())->goCheck();
        $post = $request->post();
        $userService = new User();
        $userModel = $userService->where("id = ".$post["user_id"])->find();
        if($userModel == null){ throw new FailedException(['msg'=>'用户不存在']);}

        $field = "ifNull(nickname,'') as nickname,create_time,phone,ifNull(head_img,'') as head_img,user_type";

        if($post["is_true"] == 1){
            //有效客户
            $where = [["user_type","gt","1"],["vip_time","gt","unix_timestamp(now())"],["be_invite_code","eq",$userModel["invite_code"]]];
            /**
            [sql] select * from om_user
            left join om_money_record on om_user.id = om_money_record.source_user_id
            where be_invite_code = '0983671' and user_type > 1 and vip_time > unix_timestamp(now()) */
            $list = $userService->field($field)->where($where)->paginate($post['page_number'], false, ['page' => $post['page']]);
        } else if($post["is_true"] == 0){
            //无效客户
            $map1 = [['user_type', 'eq', '1'],["be_invite_code","eq",$userModel["invite_code"]]];
            $map2 = [['user_type', 'lt', '1'],['vip_time', 'gt', 'unix_timestamp(now())'],["be_invite_code","eq",$userModel["invite_code"]]];
            $list = $userService->field($field)->whereOr([ $map1, $map2 ])->paginate($post['page_number'], false, ['page' => $post['page']]);
        }else{
            throw new FailedException(['msg'=>'当前筛选类型不存在']);
        }

        foreach ($list as $k=>$v){
            if($v["user_type"] == 1){
                $v["user_type_str"] = "普通会员";
            }elseif($v["user_type"] == 2){
                $v["user_type_str"] = "Vip会员";
            }elseif($v["user_type"] == 3){
                $v["user_type_str"] = "企业会员";
            }elseif($v["user_type"] == 4){
                $v["user_type_str"] = "企业Vip会员";
            }else{
                $v["user_type_str"] = "";
            }
        }

        return writeJson(200,$list);
    }

    /**
     * 通过手机号获取验证码
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getCode(Request $request){
        $post = $request->post();

        //获取手机号
        $userService = new User();
        $userWhere["id"] = $post["user_id"];
        $model = $userService->where($userWhere)->find();

        // 随机 生成验证码
        $code = rand(1000,9999);
        $arr['phone'] = $model['phone'];
        $arr['code']  = $code;

        // 实例化 验证码表模型
        $where[] = ['phone','eq',$model['phone']];
        $where[] = ['create_time','gt',time()-60];
        $find_res  = (new SendCode())->findOne($where);
        // 判断 是修改还是插入
        if($find_res){
            throw new FailedException(['msg'=>'该手机号在60秒内已经发送过短信']);
        }else{
            Db::startTrans();
            $res_i = (new SendCode())->dataUpdate($arr);
            if(!$res_i){
                Db::rollback();
                throw new FailedException(['msg'=>'发送失败']);
            }
            // 调取接口发验证码
            $res = sendMSM($model['phone'],$code);
            if($res['Code'] == "OK"){
                Db::commit();
                return writeJson(200,"发送成功");
            }else{
                Db::rollback();
                throw new FailedException(['msg'=>'发送失败']);
            }
        }
    }

    /**
     * 提现账单申请
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function insertOutRecord(Request $request){
        //获取当前人钱包
        $post = $request->post();
        if(!isset($post["money"]) || $post["money"] <= 0) {
            return writeJson("500",[],"金额输入有误","500");
        }
        if(!isset($post["pay_type"]) || ($post["pay_type"] != 0 && $post["pay_type"] != 1)) {
            return writeJson("200",[],"支付方式输入有误","500");
        }
        if(!isset($post["code"])) { return writeJson("200",[],"请输入验证码","500"); }

        //获取手机号
        $userService = new User();
        $userWhere["id"] = $post["user_id"];
        $userModel = $userService->where($userWhere)->find();

        $codeWhere = [['phone','eq',$userModel['phone']],['code','eq',$post['code']],['create_time','gt',time()-12000]];
        $res =(new SendCode())->findOne($codeWhere);
        if(!$res){ return writeJson("200",[],"验证码有误请重新输入","500"); }

        if ($post["pay_type"] == 0){
            //检查是否存在openId
            $userService = new User();
            $userModel = $userService->where("id = ".$post["user_id"])->find();
            if($userModel == null){ return writeJson("200",[],"用户不存在");}
            if($userModel["openid"] == null){  return writeJson("200",[],"用户openId不存在","500");}
        }else if($post["pay_type"] == 1){
            //检查支付宝支付入参
            if(!isset($post["ali_identity"])){ return writeJson("200",[],"请输入支付宝账户","500"); }
            if(!isset($post["ali_name"])){ return writeJson("200",[],"请输入支付宝名称","500"); }
        }

        //入参
        $money = $post["money"];
        $pay_type = $post["pay_type"];

        $moneyModel = $this->getMoneyByUserId($post['user_id']);
        if($moneyModel == null){
            return writeJson("200",[],"用户钱包不存在，请联系客服人员","500");
        }
        if(($moneyModel["money"] + (-$money)) < 0){
            return writeJson("200",[],"当前余额不足","500");
        }

        Db::startTrans();
        try{
            $MoneyRecordService = new MoneyRecord();
            //增减余额
            if(!$this->updateMoney($moneyModel["id"],-$money)){
                Db::rollback();
                throw new FailedException(['msg'=>'金额更新失败']);
            };

            $record = array(
               "money_id"=>$moneyModel["id"],
               "user_id"=>$moneyModel["user_id"],
               "order_number"=>(new UtilCommon())->GetRandStr2(''), //不重复的流水号
               "money_type"=>1,       //金额类型(0收入 1支出)
               "money_source_type"=>1,//账单来源(0拥金 1提现)
               "money_source_remark"=>"用户提现",//账单来源备注
               "money"=>$money, //金额
               "create_time"=>time(),//创建时间
               "audit_status"=>0,    //审核状态  (0待审核 1审核通过 2审核不通过)
               "pay_type"=>$pay_type,//支付方式  (0微信 1支付宝)
               "pay_status"=>0,      //支付状态  (0待支付 1已支付 2已取消)
               "ali_identity"=> isset($post["ali_identity"]) ? $post["ali_identity"] : "",  //支付宝账户
               "ali_name"=>     isset($post["ali_name"]) ? $post["ali_name"] : "",          //支付宝名称
            );

            if(!($MoneyRecordService->insert($record) > 0)){
                Db::rollback();
                throw new FailedException(['msg'=>'账单添加失败']);
            };
            Db::commit();
            return writeJson("200","提交成功");
        }
        catch (Exception $e){
            Db::rollback();
            throw new FailedException(['msg'=>'提交失败，原因:'.$e]);
        }
    }

    /**
     * 创建钱包-根据用户ID
     * @param $user_id
     * @return bool
     */
    public function insertMoney($user_id){
        $MoneyService = new MoneyService();
        $where["user_id"] = $user_id;
        //先判断是否存在钱包
        if($MoneyService->where($where)->count() > 0){
            return true;
        }
        //新增钱包
        $model = array(["user_id" => $user_id, "money" => 0, "credits" => 0, "is_delete" => 0]);
        if($MoneyService->dataUpdate($model) > 0){
            return true;
        }
        return false;
    }

    /**
     * 获取钱包明细 By userId
     * @param $userId
     * @return array|null|string|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getMoneyByUserId($userId){
        $MoneyService = new MoneyService();
        $where["user_id"] = $userId;
        return $MoneyService->where($where)->find();
    }

    /**
     * 钱包增减金额
     * @param $moneyId
     * @param $money
     * @return bool
     * @throws \think\Exception
     */
    private function updateMoney($moneyId,$money){
        $MoneyService = new MoneyService();
        $where["id"] = $moneyId;
        $moneyModel = $MoneyService->where($where)->find();
        if(($moneyModel["money"] + $money) < 0){
            return false;
        }
        return $MoneyService->where($where)->setInc("money",$money);
    }
}